//服务端程序
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<ctype.h>
#include<unistd.h>

int main()
{
	//创建socket
	int cfd = socket(AF_INET,SOCK_STREAM,0);
	if(cfd<0)
	{
		perror("socket error");
		return -1;
	}	

	//链接服务端
	struct sockaddr_in cli;
	cli.sin_family = AF_INET;
	cli.sin_port = htons(6666);
	inet_pton(AF_INET,"127.0.0.1",&cli.sin_addr.s_addr);

	int ret = connect(cfd,(struct sockaddr*)&cli,sizeof(cli));
	if(ret<0)
	{
		perror("connect error");
		return -1;
	}

	int n = 0;
	char buf[256];

	while(1)
	{
		//读标准输入数据
		memset(buf,0,sizeof(buf));
		int n = read(STDIN_FILENO,buf,sizeof(buf));	
		//发送数据
		write(cfd,buf,n);
		//读服务端发来的数据
		memset(buf,0,sizeof(buf));
		n = read(cfd,buf,sizeof(buf));
		if(n<=0)
		{
			printf("read error or server closed,n==[%d]\n",n);
		}
		printf("n==[%d],buf=[%s]\n",n,buf);
	}

	//关闭监听文件描述符和通信文件描述符
	close(cfd);
	return 0;
}
